package com.tsingteng.cosfun.widget.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLVideoFilterListener;
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener;
import com.qiniu.pili.droid.shortvideo.PLWatermarkSetting;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.App;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.utils.AlbumNotifyHelper;
import com.tsingteng.cosfun.utils.FileDownUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.CompletedView;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

//评论选择回复或举报
public class DownLoadProgressDialog extends Dialog  {
    public DownLoadProgressDialog(Context context) {
        super(context);
    }

    public DownLoadProgressDialog(Context context, int theme) {
        super(context, theme);
    }



    private static final String TAG = "DownLoadProgressDialog";
    public static class Builder {
        //        private OnItemClickListener onItemClickListener;
        private View layout;
        private CompletedView completedView = null;
        private TextView progress_tv;
        private DownLoadProgressDialog dialog;
        Activity mContext = null;
        String url;
        public File file;
        private PLWatermarkSetting mWatermarkSetting;
        private PLVideoEditSetting setting;
        private PLShortVideoEditor mShortVideoEditor;

        public Builder(Activity context, Activity activity) {
            mContext = context;
            dialog = new DownLoadProgressDialog(context, R.style.commselectDialog);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            layout = inflater.inflate(R.layout.download_progress_dialog, null);
            dialog.addContentView(layout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        }
        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        /**
         * 创建单按钮对话框
         *
         * @return
         */
        public DownLoadProgressDialog createDialog() {
            completedView = layout.findViewById(R.id.download_progressbar);
            progress_tv = layout.findViewById(R.id.download_progress);
            completedView.setMaxProgress(100);
            create();
            download(url);
            return dialog;
        }

        /**
         * 单按钮对话框和双按钮对话框的公共部分在这里设置
         */
        private void create() {
            dialog.setContentView(layout);
            dialog.setCancelable(false);     //用户可以点击手机Back键取消对话框显示
            dialog.setCanceledOnTouchOutside(false);        //用户不能通过点击对话框之外的地方取消对话框显示
            mWatermarkSetting = new PLWatermarkSetting();
            mWatermarkSetting.setSize(0.4f,0.1f);
            mWatermarkSetting.setResourceId(R.drawable.watermark);
            mWatermarkSetting.setPosition(0.01f, 0.01f);
            mWatermarkSetting.setAlpha(128);

        }

        public void download(String url) {
            Log.e("test1", "下载路径=" + url);
            String saveUrl = getSaveDownPath(url);
            if (saveUrl == null) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                return;
            }
            setting = new PLVideoEditSetting();
            setting.setSourceFilepath(saveUrl);
            String destFilePath = getdestDownPath(saveUrl);
            setting.setDestFilepath(destFilePath);
            Log.e("test1", "保存路径=" + saveUrl);
            FileDownUtils.getIntance().starSingleDown(mContext, url, saveUrl, new FileDownUtils.OnCompleteListener() {
                @Override
                public void onComplete() {
//                    updateVideo(saveUrl);
                    //将视屏加水印,然后将原视频删除
//                    if (dialog != null) {
//                        dialog.dismiss();
//                    }
//                    Uri localUri = AlbumNotifyHelper.insertVideoToMediaStore(mContext,saveUrl,System.currentTimeMillis(),0,0,0);
//                    Toast.makeText(mContext, "已保存到本地", Toast.LENGTH_SHORT).show();
////                    Uri localUri = Uri.parse("file://" + saveUrl);
//                    Intent localIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
//                    localIntent.setData(localUri);
//                    mContext.sendBroadcast(localIntent);
                    //客户端生成带水印的视频比较慢，建议后端直接生成，客户端只需下载
                    addWatermarkVideo(saveUrl);
                }

                @Override
                public void onStart() {

                }

                @Override
                public void onPregress(int progress) {
                    progress_tv.setText(progress + "%");
                    completedView.setProgress(progress);
                }

                @Override
                public void onError() {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                }
            });
        }

        private void addWatermarkVideo(String saveUrl) {
            mShortVideoEditor = new PLShortVideoEditor(new GLSurfaceView(mContext), setting);
            mShortVideoEditor.setVideoSaveListener(new PLVideoSaveListener() {
                @Override
                public void onSaveVideoSuccess(String s) {
                    LogUtils.e(TAG,"成功"+ s);
                    Log.e("test1", "通知相册刷新");
                    mContext.runOnUiThread(() -> {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        Uri localUri = AlbumNotifyHelper.insertVideoToMediaStore(mContext,s,System.currentTimeMillis(),0,0,0);
                        Toast.makeText(mContext, "已保存到本地", Toast.LENGTH_SHORT).show();
//                            Uri localUri = Uri.parse("file://" + s);
                        Intent localIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
                        localIntent.setData(localUri);
                        mContext.sendBroadcast(localIntent);
                    });
                }

                @Override
                public void onSaveVideoFailed(int i) {
                    LogUtils.e(TAG,"失败"+ i);
                    dismissDialog();
                }

                @Override
                public void onSaveVideoCanceled() {
                    LogUtils.e(TAG,"取消");
                    dismissDialog();
                }

                @Override
                public void onProgressUpdate(float v) {
                    LogUtils.e(TAG,"onProgressUpdate"+v);
                    mContext.runOnUiThread(() -> completedView.setProgress((int) (100 * v)));
                }
            });
            mShortVideoEditor.save(new PLVideoFilterListener() {
                @Override
                public void onSurfaceCreated() {

                }

                @Override
                public void onSurfaceChanged(int i, int i1) {

                }

                @Override
                public void onSurfaceDestroy() {

                }

                @Override
                public int onDrawFrame(int i, int i1, int i2, long l, float[] floats) {
                    mShortVideoEditor.updateSaveWatermark(mWatermarkSetting);
                    return i;
                }
            });
        }
      void dismissDialog(){
          mContext.runOnUiThread(() -> {
              if (dialog != null) {
                  dialog.dismiss();
              }
          });
      }

    }



    private static String getSavePath(String url) {
        String path = VideoUtils.videoSavePath;
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        String name = url.substring(url.lastIndexOf("/") + 1, url.length());
        File file = new File(path + name);
        if (file.exists()) {
//            Toast.makeText(App.getContext(), "视频已下载过", Toast.LENGTH_SHORT).show();
//            return null;
        }
        return path + name;
    }
    private static String getSaveDownPath(String url) {
        String path = VideoUtils.videoDownPath;
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        String name = url.substring(url.lastIndexOf("/") + 1, url.length());
        File file = new File(path + name);
        if (file.exists()) {
//            Toast.makeText(App.getContext(), "视频已下载过", Toast.LENGTH_SHORT).show();
//            return null;
        }
        return path + name;
    }
    private static String getdestDownPath(String url) {
        String path = VideoUtils.videoDownPath;
        if (TextUtils.isEmpty(url)) {
            return null;
        }
        String name = System.currentTimeMillis() + LogonUtils.getProFildId()+ "cos_fun.mp4";
        File file = new File(path + name);
        if (file.exists()) {
//            Toast.makeText(App.getContext(), "视频已下载过", Toast.LENGTH_SHORT).show();
//            return null;
        }
        return path + name;
    }
}
